<?php
namespace Wap\Controller;

use User\Model\WechatShareModel;
use Wap\Service\WeixinService;

class AnniversaryController extends WapController
{
    public $wxToken;//活动绑定的微信号

    public function __construct()
    {
        parent::__construct();
        $this->wxToken = 'iequde1415960341';
        $this->handleCriteriaWxuser();
    }

    //微信公众号信息
    private function handleCriteriaWxuser()
    {
        $this->wxuser = WeixinService::getWxuser($this->wxToken);
    }

    public function index()
    {
        $openid = session('anniversary_openid');
        if(!empty($openid)){
            $wx = WeixinService::getWxuser($this->wxToken);
            $wxJSApi = WeixinService::buildWXJSApi($wx);
            if (!empty($wxJSApi)) {
                $data = array(
                    'appId' => $wx['appid'],
                    'nonceStr' => $wxJSApi['noncestr'],
                    'wxTicket' => $wxJSApi['ticket'],
                    'timestamp' => $wxJSApi['timestamp'],
                    'wxSha1' => $wxJSApi['sha1']
                );
            }
            $this->assign('shareData', $data);
            $this->display();
        }else{
            $wechat = new \Wap\Service\WechatService($this->wxuser['appid'], $this->wxuser['appsecret']);
            $url = $wechat->buildOauthURI("http://$_SERVER[HTTP_HOST]/Wap/Anniversary/third");
            redirect($url);
        }
    }

    public function third()
    {
        $code = I("get.code", "", "");
        $wechat = new \Wap\Service\WechatService($this->wxuser['appid'], $this->wxuser['appsecret']);
        $openid = $wechat->snsapiBaseUser($code);
        session('anniversary_openid', $openid);
        $this->display('index');
    }

    //微信分享页面增加红包雨抽奖机会
    public function gameChance(){
        $openid = session('anniversary_openid');
        if(!$this->wxToken){
            $this->ajaxReturn( array('status' => -1, 'result' => '未获得token，分享获得机会失败') );
        }
        if(!$openid){
            $this->ajaxReturn( array('status' => -1, 'result' => '未获得openid，分享获得机会失败') );
        }
        $data = array(
            'token' => $this->wxToken,
            'openid' => $openid,
            'url' => 'http://esm.zbxinmeiti.com/Wap/RedPacket/index?id=3'
        );
        $added = M("wechat_share")->add($data);
        if($added){
            $this->ajaxReturn( array('status' => 1, 'result' => '额外增加一次抽奖机会成功') );
        }else{
            $this->ajaxReturn( array('status' => 0, 'result' => '额外增加一次抽奖机会失败') );
        }
    }
}